var generator = require('../generator/generator');
var performance = require('../model/performance');
var performance_term = require('../model/performance_term');
var log = require('../model/log');
var item = require('../model/item');
var mail = require("nodemailer").mail;
var fs = require('fs');
var config = require('../../config/config');


exports.savePer = function(req, res, connection) {
	// res.send("save performance");
	var sendData = req.body;
	var lastChange = req.user.employeeId;
	// console.log("savePer----", sendData);
	var basicItems = sendData.basicItems;
	var perData = {
		// assessmentPersonId: sendData.assessmentPersonId,
		departmentId: sendData.departmentId,
		perfDate: sendData.perfDate,
		employeeId: sendData.employeeId,
		state: 0,
		score: 0,
		level: 'E',
		lastChange: lastChange,
		preDeptId: sendData.preDeptId,
		project: sendData.project
	};
	performance.insertPerf(connection, perData, basicItems, function(insertId) {
		// console.log("result-------", result);
		if (insertId != null && insertId != "") {
			performance.updateAssPersonId(connection, insertId);
			//添加历史记录
			performance_term.selTermByPid(connection, insertId, function(results) {
				var sendLogData = {};
				sendLogData.perfData = perData;
				if (results != null) {
					sendLogData.termsData = results;
				}
				var logData = {
					itemId: insertId,
					updatePersonId: req.user.employeeId,
					content: JSON.stringify(sendLogData),
					type: 1,
					operation: '填写',
				};
				log.addLog(connection, logData, function(rows) {
					
				});
			});
			// var logData = {
			// 	itemId: result,
			// 	updatePersonId: req.user.employeeId,
			// 	content: JSON.stringify(sendData),
			// 	type: 1,
			// 	operation: '填写',
			// };
			// log.addLog(connection, logData, function(rows) {
			// 	// console.info("log--rows");
			// 	// console.info(rows);
			// });
			var toAddress = "";
			var newRows = [];
			var json = {};
			for(var i = 0; i < basicItems.length; i++){
				if(!json[basicItems[i].assPersonEmail]){
					newRows.push(basicItems[i]);
					json[basicItems[i].assPersonEmail] = 1;
				}
			}

			for (var i = 0; i < newRows.length; i++) {
				// console.log(res[i].assPersonEmail);
				if (i == 0) {
					toAddress = newRows[i].assPersonEmail;
				} else {
					toAddress = toAddress + "," + newRows[i].assPersonEmail;
				}
			}
			var img = fs.readFileSync(config.root + "/public/assets/images/foss.png"); //导入图片  
			  
			var attachment_list = [  
			{  
			    'filename': 'attachment1.txt', //这里只是给附件取名称，而不是导入文件内容  
			    'contents': 'contents for attachment1.txt' //引入附件  
			},
			{  
			    'filename': 'аттачмент2.bin',  
			    'contents': new Buffer('binary contents', 'binary')
			}, 
			{  
			    'filename': "foss.png",  
			    'contents': img //导入图片文件  
			}  
			  
			];
			var cid_value = Date.now() + '.image.jpg';  
			  					  
			var attachments = [{  
			  
			    filename: 'foss.png',  
			  
			    contents: img,  
			  
			    cid: cid_value  
			  
			}]; 
			var sendMsg = "<br/>&nbsp;各位同事：<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + sendData.employee + "下个月的绩效目标已填写，请查看。</b><br/>&nbsp;<br/>&nbsp;<div><span><div style='font-size: 10.0pt;font-family: verdana;margin: 10.0px;'><div><table class='MsoNormalTable' style='border-collapse: collapse;margin-left: 5.4pt;' cellspacing='0' cellpadding='0' border='0'><tbody><tr style='height: 68.75pt;'><td style='height: 68.75pt;width: 116.6pt;padding-bottom: 0.0cm;padding-top: 0.0cm;padding-left: 0.0cm;padding-right: 0.0cm;' valign='top' width='155'><p class='MsoNormal' style='margin: 0.5cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: black;'><img src='cid:" + cid_value + "' /></span></b></p></td><td style='height: 68.75pt;width: 291.75pt;padding-bottom: 0.0cm;padding-top: 0.0cm;padding-left: 5.4pt;padding-right: 5.4pt;' valign='top' width='389'><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><span style='font-family: times new roman , serif;color: navy;'>&nbsp;</span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>广州人事行政部</span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>恒拓开源<span>(</span>天津<span>)</span>信息科技有限公司</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>Forever Open Source Software INC.</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>广州市白云区云霄路<span>89</span>号云霄大厦二楼<span></span></span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>YunXiaoDaSha Plaza NO.89 YuXiaoLu 3 St.BaiYun District,GuangZhou</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>电话</span></b><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>: 020-66836611&nbsp;&nbsp;&nbsp; 36700150&nbsp;&nbsp;&nbsp; </span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'></span></b><b><span style='font-size: 9.0pt;color: gray;'>官方网站</span></b><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>: </span></b><span style='color: navy;'><a href='http://www.foreveross.com/' target='_blank'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>http://www.foreveross.com/</span></b></a></span><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'></span></b></p></td></tr></tbody></table></div></div></span></div>"
			mail({
				from: 'gz-hr@foreveross.com',
				to: toAddress,
				subject: "人事管理系统绩效填写提醒",
				html: sendMsg,
				attachments: attachments
			});
			res.send("绩效信息保存成功！");
		} else {
			res.send("绩效信息保存失败！");
		}

	});

};
exports.selEmpPerfs = function(req, res, connection) {
	// console.log("req.user:", req.user);
	// res.send("test user");
	var year = req.query.year;
	// console.log("year=" + year);
	var user = req.user;
	if (user.employeeId != null && user.employeeId != 0) {
		performance.selPerByEmp(connection, user.employeeId, year, function(rows) {
			res.send(rows);
		});
	} else {
		res.send(null);
	}

};

exports.selMonthPerf = function(req, res, connection) {
	var user = req.user;
	var timeStr = req.params['timeStr'];
	// console.log("controller---timeStr =",timeStr);
	var sendResult = {};
	if (user.employeeId != null && user.employeeId != 0) {
		performance.selEmpPerfMonth(connection, user.employeeId, timeStr, function(rows) {
			// res.send(rows);
			sendResult.perData = rows;
			if (rows != null && rows.length != 0) {
				performance_term.selTermByPid(connection, rows[0].id, function(results) {
					if (results != null) {
						sendResult.termsData = results;
					}
					res.send(sendResult);
				});
			} else {
				res.send(sendResult);
			}
		});
	}
	// performance.selEmpPerfMonth(connection, user.employeeId, timeStr, function(rows) {
	// 	// res.send(rows);
	// 	sendResult.perData = rows;
	// 	if(rows != null && rows.length !=0) {
	// 		performance_term.selTermByPid(connection, rows[0].id, function(results) {
	// 			if(results != null){
	// 				sendResult.termsData = results;
	// 			}
	// 			res.send(sendResult);
	// 		});
	// 	}else{
	// 		res.send(sendResult);
	// 	}
	// });
};

exports.singlePerf = function(req, res, connection) {
	var user = req.user;
	var timeStr = req.params['timeStr'];
	if (user.employeeId != null && user.employeeId != 0) {

		performance.selPerByEmp(connection, user.employeeId, timeStr, function(rows) {
			var sendResult = {
				rows: rows
			};
			item.selAccess(connection, "填写", function(result) {
				if (result != null && result.length != 0 && result[0].value == "true") {
					sendResult.access = result[0].showValue;
				}
				res.send(sendResult);
			});
			// res.send(rows);
		});
	}
	// performance.selEmpPerfMonth(connection, user.employeeId, timeStr, function(rows) {
	// 	res.send(rows);
	// });
};

exports.delPerfTerm = function(req, res, connection) {
	var termId = req.query.termId;
	performance_term.deletePerTerm(connection, termId, function(rows) {
		//console.log("delPerfTerm--rows:", rows);
		res.send("success");
	});
};

exports.updateEmpPerf = function(req, res, connection) {
	var operation = "修改";
	var sendData = req.body;
	var user = req.user;

	var basicItems = sendData.basicItems;
	var updateItems = sendData.updateItems;
	var deleteItems = sendData.deleteItems;
	var perfId = sendData.perfId;
	// console.log("updateEmpPerf--updateItems:", updateItems);

	var perData = {
		// assessmentPersonId: sendData.assessmentPersonId,
		departmentId: sendData.departmentId,
		perfDate: sendData.perfDate,
		employeeId: sendData.employeeId,
		perfId: perfId,
		score: 0,
		level: "E",
		state: 0,
		// comment: sendData.comment,
		preDeptId: sendData.preDeptId,
		lastChange: user.employeeId,
		project: sendData.project
	};

	performance.updatePerf(connection, basicItems, updateItems, deleteItems, perData, function(result) {
		// console.log("updateEmpPerf---insertId:", result);
		//修改任务及目标的权重
		performance.updateAssPersonId(connection, perfId);
		var updateData = {};
		performance_term.selUncheckTermByPid(connection, perfId, function(rows) {
			// console.log("selUncheckTermByPid---rows:", rows);
			//所有绩效项的状态都为1时绩效的状态才能为1，否则为0
			if (rows != null && rows.length != 0) {
				updateData.state = 0;
				updateData.level = "E";
				updateData.score = 0;
				updateData.perfId = perfId;
				performance.updPerf(connection, updateData, function(result2) {
					var toAddress = "";
					if (basicItems != undefined) {
						for (var i = 0; i < basicItems.length; i++) {
							if (i == 0) {
								toAddress = basicItems[i].assPersonEmail;
							} else {
								toAddress = toAddress + "," + basicItems[i].assPersonEmail;
							}
						}
					}
					for (var j = 0; j < updateItems.length; j++) {
						// console.log(toAddress);
						if (j == 0) {
							toAddress = updateItems[j].assPersonEmail;
						} else {
							toAddress = toAddress + "," + updateItems[j].assPersonEmail;
						}
					}
					var img = fs.readFileSync(config.root + "/public/assets/images/foss.png"); //导入图片  
					  
					var attachment_list = [  
					{  
					    'filename': 'attachment1.txt', //这里只是给附件取名称，而不是导入文件内容  
					    'contents': 'contents for attachment1.txt' //引入附件  
					},
					{  
					    'filename': 'аттачмент2.bin',  
					    'contents': new Buffer('binary contents', 'binary')
					}, 
					{  
					    'filename': "foss.png",  
					    'contents': img //导入图片文件  
					}  
					  
					];
					var cid_value = Date.now() + '.image.jpg';  
					  					  
					var attachments = [{  
					  
					    filename: 'foss.png',  
					  
					    contents: img,  
					  
					    cid: cid_value  
					  
					}]; 
					var sendMsg = "<br/>&nbsp;各位同事：<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + sendData.employee + "下个月的绩效目标已修改，请查看。</b><br/>&nbsp;<br/>&nbsp;<div><span><div style='font-size: 10.0pt;font-family: verdana;margin: 10.0px;'><div><table class='MsoNormalTable' style='border-collapse: collapse;margin-left: 5.4pt;' cellspacing='0' cellpadding='0' border='0'><tbody><tr style='height: 68.75pt;'><td style='height: 68.75pt;width: 116.6pt;padding-bottom: 0.0cm;padding-top: 0.0cm;padding-left: 0.0cm;padding-right: 0.0cm;' valign='top' width='155'><p class='MsoNormal' style='margin: 0.5cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: black;'><img src='cid:" + cid_value + "' /></span></b></p></td><td style='height: 68.75pt;width: 291.75pt;padding-bottom: 0.0cm;padding-top: 0.0cm;padding-left: 5.4pt;padding-right: 5.4pt;' valign='top' width='389'><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><span style='font-family: times new roman , serif;color: navy;'>&nbsp;</span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>广州人事行政部</span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>恒拓开源<span>(</span>天津<span>)</span>信息科技有限公司</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>Forever Open Source Software INC.</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>广州市白云区云霄路<span>89</span>号云霄大厦二楼<span></span></span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>YunXiaoDaSha Plaza NO.89 YuXiaoLu 3 St.BaiYun District,GuangZhou</span></b><span style='color: navy;'></span></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;color: gray;'>电话</span></b><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>: 020-66836611&nbsp;&nbsp;&nbsp; 36700150&nbsp;&nbsp;&nbsp; </span></b></p><p class='MsoNormal' style='margin: 0.0cm 0.0cm 0.0pt;'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'></span></b><b><span style='font-size: 9.0pt;color: gray;'>官方网站</span></b><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>: </span></b><span style='color: navy;'><a href='http://www.foreveross.com/' target='_blank'><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'>http://www.foreveross.com/</span></b></a></span><b><span style='font-size: 9.0pt;font-family: arial , sans-serif;color: gray;'></span></b></p></td></tr></tbody></table></div></div></span></div>"
					console.log("toAddress--",toAddress);
					mail({
						from: 'gz-hr@foreveross.com',
						to: toAddress,
						subject: "人事管理系统绩效修改提醒",
						html: sendMsg,
						attachments: attachments //如果要发送附件  
					});
					// mail({
					// 	from: req.user.email,
					// 	to: toAddress,
					// 	subject: "绩效修改",
					// 	html: "<b>绩效修改</b>"
					// });
					res.send("绩效信息保存成功！");
				});
			} else {
				updateData.state = 1;
				performance_term.selCheckedTermByPid(connection, perfId, function(data) {
					// console.log("selCheckedTermByPid---data:", data);
					if (data != null && data.length != 0) {
						var basicScore = 0; //工作任务及目标总分
						var plusScore = 0; //加分项总分
						var professionalScore = 0; //职业化标准总分
						for (var i = 0; i < data.length; i++) {
							var item = data[i];
							if (item.type == 0) {
								basicScore += parseFloat(item.score) * parseFloat(item.weight) / 100;
							} else if (item.type == 1) {
								plusScore += parseFloat(item.score);
							} else {
								professionalScore += parseFloat(item.score) * parseFloat(item.weight) / 100;
							}
						}
						if (plusScore > 20) {
							plusScore = 20;
						}
						// console.log("basicScore = " + basicScore + "-----plusScore = " + plusScore + "---professionalScore = " + professionalScore)
						var perfScore = (basicScore * 0.7) + plusScore + (professionalScore * 0.3);
						var level = "";
						if (perfScore >= 100) {
							level = "A";
						} else if (perfScore >= 85 && perfScore < 100) {
							level = "B";
						} else if (perfScore >= 75 && perfScore < 85) {
							level = "C";
						} else if (perfScore >= 60 && perfScore < 75) {
							level = "D";
						} else {
							level = "E";
						}
						updateData.level = level;
						updateData.score = Math.round(perfScore * 100) / 100;
						updateData.perfId = perfId;
						// console.log("updateData", updateData);

						performance.updPerf(connection, updateData, function(result2) {

							res.send("绩效信息保存成功！");
						});
					}
				});
			}

			// 历史记录
			var sendLogData = {};
			performance.findPerfById(connection, perfId, function(rows) {
				// console.log("getPerfById--rows:", rows);
				sendLogData.perfData = rows[0];

				performance_term.selTermByPid(connection, rows[0].id, function(results) {
					if (results != null) {
						sendLogData.termsData = results;
					}
					var logData = {
						itemId: perfId,
						updatePersonId: req.user.employeeId,
						content: JSON.stringify(sendLogData),
						type: 1,
						operation: sendData.operation,
					};
					log.addLog(connection, logData, function(rows) {
						// console.info("log--rows");
						// console.info(rows);
					});
				});
				// var logData = {
				// 	itemId: perfId,
				// 	updatePersonId: req.user.employeeId,
				// 	content: JSON.stringify(sendLogData),
				// 	type: 1,
				// 	operation: sendData.operation,
				// };
				// log.addLog(connection, logData, function(rows) {
				// 	// console.info("log--rows");
				// 	// console.info(rows);
				// });

			});
			// 历史记录结束
		});
	});



};

exports.selMonthPerfsByAss = function(req, res, connection) {

	var sendData = req.query.sendData;
	var jsonData = JSON.parse(sendData);
	var stateKey = jsonData.stateKey;
	// console.log("jsonData:", jsonData);
	var time = jsonData.time;
	var item = jsonData.item;
	var index = jsonData.index;
	var begin = item * (index - 1);
	var end = item * index - 1;
	var user = req.user;

	if (user.employeeId != null && user.employeeId != 0) {
		performance.selMonthPerfsByAss(connection, user.employeeId, time, stateKey, function(rows) {

			var perfData = [];
			var k = 0;
			for (var i = begin; i < end + 1; i++) {
				if (i < rows.length) {
					perfData[k] = rows[i];
					k++;
				}
			}
			var sendData = {
				data: perfData,
				count: rows.length
			};
			res.send(sendData);
		});
	}

};

exports.selPerfsByAss = function(req, res, connection) {

	var item = req.query.item;
	var index = req.query.index;
	var keyword = req.query.keyword;
	var searchTime = req.query.searchTime;
	var begin = item * (index - 1);
	var end = item * index - 1;
	var user = req.user;

	if (user.employeeId != null && user.employeeId != 0) {
		performance.selPerfsByAss(connection, user.employeeId, keyword, searchTime, function(rows) {
			var data = [];
			var k = 0;
			for (var i = begin; i < end + 1; i++) {
				if (i < rows.length) {
					data[k] = rows[i];
					k++;
				}
			}
			var sendData = {
				data: data,
				count: rows.length
			};
			res.send(sendData);
		});
	}
	// performance.selPerfsByAss(connection, user.employeeId, keyword, searchTime, function(rows) {
	// 	var data = [];
	// 	var k = 0; 
	// 	for(var i = begin; i < end + 1; i++) {
	// 		if(i < rows.length) {
	// 			data[k] = rows[i];
	// 			k++;
	// 		}
	// 	}
	// 	var sendData = {
	// 		data: data,
	// 		count: rows.length
	// 	};
	// 	res.send(sendData);
	// });
};

exports.getPerfById = function(req, res, connection) {
	var perfId = req.params['perfId'];
	// console.log("getPerfById--perfId:" + perfId);
	var user = req.user;
	var sendResult = {};
	performance.findPerfById(connection, perfId, function(rows) {
		// console.log("getPerfById--rows:", rows);
		sendResult.perfData = rows[0];
		if (rows != null && rows.length != 0) {
			if (user.employeeId != null && user.employeeId != 0) {
				performance_term.selTermByPidAssm(connection, rows[0].id, user.employeeId, function(results) {
					if (results != null) {
						sendResult.termsData = results;
					}
					res.send(sendResult);
				});
			} else {
				res.send(sendResult);
			}
			// performance_term.selTermByPid(connection, rows[0].id, function(results) {
			// 		if(results != null){
			// 			sendResult.termsData = results;
			// 		}
			// 		res.send(sendResult);
			// 	});
		} else {
			res.send(sendResult);
		}

	});
};

exports.selHisPerfs = function(req, res, connection) {
	var user = req.user;
	// var timeStr = req.query.timeStr;
	var item = req.query.item;
	var index = req.query.index;
	var begin = item * (index - 1);
	var end = item * index - 1;

	if (user.employeeId != null && user.employeeId != 0) {
		performance.selEmpHisPerf(connection, user.employeeId, function(rows) {
			// res.send(rows);
			var data = [];
			var k = 0;
			for (var i = begin; i < end + 1; i++) {
				if (i < rows.length) {
					data[k] = rows[i];
					k++;
				}
			}
			var sendData = {
				data: data,
				count: rows.length
			};
			res.send(sendData);
		});
	}
	// performance.selEmpHisPerf(connection, user.employeeId, function(rows) {
	// 	// res.send(rows);
	// 	var data = [];
	// 	var k = 0; 
	// 	for(var i = begin; i < end + 1; i++) {
	// 		if(i < rows.length) {
	// 			data[k] = rows[i];
	// 			k++;
	// 		}
	// 	}
	// 	var sendData = {
	// 		data: data,
	// 		count: rows.length
	// 	};
	// 	res.send(sendData);
	// });

};

//校验某一员工同一月份的绩效是否存在
exports.checkExist = function(req, res, connection) {
	var empId = req.query.empId;
	var perfDate = req.query.perfDate;
	// console.log("empid=" + empId + "---perfDate=" + perfDate);
	performance.selPerfByEmpDate(connection, empId, perfDate, function(rows) {
		// console.log("checkExist---rows", rows);
		// var sendResult = true;
		// if(rows != null && rows.length != 0) {
		// 	sendResult = false;
		// }
		res.send(rows);
	});
};
//根据员工id及考核周期查询绩效及绩效项信息
exports.selPerfDetail = function(req, res, connection) {
	var empId = req.query.empId;
	var perfDate = req.query.perfDate;
	performance.selDetailByEmpDate(connection, empId, perfDate, function(rows) {
		var sendData = {};
		if(rows != null && rows.length != 0) {
			sendData.perfData = rows[0];
			var type = 1;
			log.selectItemLog(connection, rows[0].id, type, function(items) {
				sendData.logData = items;
			});
			performance_term.selTermByPid(connection, rows[0].id, function(results) {
				sendData.termsData = results;
				var type = 1;
				log.selectItemLog(connection, rows[0].id, type, function(items) {
					sendData.logData = items;
					res.send(sendData);
				});
				// res.send(sendData);
			});
		}else{
			res.send(sendData);
		}
		
	});
};

exports.checkAssignmentIdExit = function(req, res, connection) {
	var id = req.query.id;
	var date = req.query.date;
	var date_next = req.query.date_next;
	var data = {
		id: id,
		date: date,
		date_next: date_next
	};
	performance.checkAssignmentIdExit(connection, data, function(rows) {
		// console.log('dadadad', rows.length);
		if (rows.length == 0) {
			res.send("false");
		} else {
			res.send("true");
		}
	});
};

exports.changeState = function(req, res, connection) {
	var data = req.body;
	// console.log('changeState--data', data);

	performance.changeState(connection, data, function(rows) {
		// console.log('rrrrrrrr', rows);
		//console.log('data', data);
		// 历史记录
		for (var i = 0; i < data.ids.length; i++) {
			// console.info("data.ids[i]-----", data.ids[i]);
			var logData = {
				itemId: data.ids[i],
				updatePersonId: req.user.employeeId,
				type: 1,
				operation: "确认" //data.operation,
			};
			var sendLogData = {};
			performance.findPerfById(connection, data.ids[i], function(rows) {
				// console.log("getPerfById--rows:", rows);
				sendLogData.perfData = rows[0];

				performance_term.selTermByPid(connection, rows[0].id, function(results) {
					if (results != null) {
						sendLogData.termsData = results;
					}
					logData.content = JSON.stringify(sendLogData);
					log.addLog(connection, logData, function(rows) {

					});
				});
				// logData.content = JSON.stringify(sendLogData);
				// log.addLog(connection, logData, function(rows) {
				// 	// console.info("log--rows");
				// 	// console.info(rows);
				// });

			});
		} // 历史记录结束
		res.send(rows);
	});
};

exports.returnPerf = function(req, res, connection) {
	var data = req.body;
	var perfId = data.id;
	performance.returnPerf(connection, data, function(rows) {
		var sendLogData = {};
		performance.findPerfById(connection, perfId, function(rows) {
			// console.log("getPerfById--rows:", rows);
			sendLogData.perfData = rows[0];

			performance_term.selTermByPid(connection, rows[0].id, function(results) {
				if (results != null) {
					sendLogData.termsData = results;
				}
				var logData = {
					itemId: perfId,
					updatePersonId: req.user.employeeId,
					content: JSON.stringify(sendLogData),
					type: 1,
					operation: data.operation,
				};
				log.addLog(connection, logData, function(rows) {
					
				});
			});
			// var logData = {
			// 	itemId: perfId,
			// 	updatePersonId: req.user.employeeId,
			// 	content: JSON.stringify(sendLogData),
			// 	type: 1,
			// 	operation: data.operation,
			// };
			// log.addLog(connection, logData, function(rows) {
			// 	// console.info("log--rows");
			// 	// console.info(rows);
			// });

		});
		res.send(rows);
	});
};
exports.selectPerTerm = function(req, res, connection) {
	var perfId = req.params['id'];
	var sendResult = {};
	performance.findPerfById(connection, perfId, function(rows) {
		// console.log("getPerfById--rows:", rows);
		sendResult.perfData = rows[0];
		if (rows != null && rows.length != 0) {
			// console.log(11);
			var type = 1;
			log.selectItemLog(connection, rows[0].id, type, function(items) {
				sendResult.logData = items;
				// console.log("sendResult.logData =",items);
			});
			item.selAccess(connection, "退回", function(accessRows) {
				if (accessRows != null && accessRows.length != 0 && accessRows[0].value == "true") {
					sendResult.access = "退回";
				}
			});
			performance_term.selectPerTerms(connection, rows[0].id, function(results) {
				if (results != null) {
					sendResult.termsData = results;
				}
				res.send(sendResult);
			});
		} else {
			res.send(sendResult);
		}

	});
};

exports.changeWeight = function(req, res, connection) {
	var data = req.body;
	// console.log('data', data);
	performance.changeWeight(connection, data.data, function(data) {
		res.send(data);
	});
};
